﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using RabbitManage.Code;

namespace RabbitManage
{
    public class MyHttpModule : IHttpModule
    {

        public void Dispose() { }

        public void Init(HttpApplication context)
        {

            //context.BeginRequest += new EventHandler(Application_BeginRequest);

            //context.EndRequest += new EventHandler(Application_EndRequest);

            context.AuthenticateRequest += context_AuthenticateRequest;
        }

        void context_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication) sender;
            HttpContext context = application.Context;
            HttpRequest request = context.Request;
            string url = request.Url.AbsolutePath.ToLower();

            if (url.Contains("logon") || url.Contains("register")) return;

#if(DEBUG)
            if (!url.EndsWith(".aspx")) return;
#endif

            //tmp solution, should use encrypt variable ticket, not the easy uid 
            HttpCookie cookie = request.Cookies[Constant.CookieName];
            if (cookie == null || string.IsNullOrEmpty(cookie.Values[Constant.CookieUid]))
            {
                context.Response.Redirect(Constant.LogonPage, false);
                return;
            }

            //HttpCookie authCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
            //FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);//解密
            //string[] roles = authTicket.UserData.Split(new char[] { ';' });//根据存入时的格式分解，;或|....
            //context.User = new GenericPrincipal(context.User.Identity, Roles);//存到HttpContext.User中 

            //HttpCookie cookie = null;

            //////////////////////////////////////////////////////////////
            //// Step 1: If there are event handlers, invoke the handlers
            //if (_eventHandler != null)
            //    _eventHandler(this, e);

            ////////////////////////////////////////////////////////////// 
            //// Step 2: Check if the event handler created a user-object
            //if (e.Context.User != null)
            //{
            //    // do nothing because someone else authenticated
            //    return;
            //}

            //if (e.User != null)
            //{
            //    // the event handler created a user 
            //    e.Context.SetPrincipalNoDemand(e.User);
            //    return;
            //}

            //////////////////////////////////////////////////////////////
            //// Step 3: Extract the cookie and create a ticket from it
            //bool cookielessTicket = false;
            //FormsAuthenticationTicket ticket = ExtractTicketFromCookie(e.Context, FormsAuthentication.FormsCookieName, out cookielessTicket);

            ////////////////////////////////////////////////////////////// 
            //// Step 4: See if the ticket was created: No => exit immediately
            //if (ticket == null || ticket.Expired)
            //    return;

            //////////////////////////////////////////////////////////////
            //// Step 5: Renew the ticket 
            //FormsAuthenticationTicket ticket2 = ticket;
            //if (FormsAuthentication.SlidingExpiration)
            //    ticket2 = FormsAuthentication.RenewTicketIfOld(ticket);

            ////////////////////////////////////////////////////////////// 
            //// Step 6: Create a user object for the ticket
            //e.Context.SetPrincipalNoDemand(new GenericPrincipal(new FormsIdentity(ticket2), new String[0]));

            ////////////////////////////////////////////////////////////// 
            //// Step 7: Browser does not send us the correct cookie-path
            ////         Update the cookie to show the correct path 
            //if (!cookielessTicket && !ticket2.CookiePath.Equals("/"))
            //{
            //    cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName];
            //    if (cookie != null)
            //    {
            //        cookie.Path = ticket2.CookiePath;
            //    }
            //}

            ////////////////////////////////////////////////////////////// 
            //// Step 8: If the ticket was renewed, save the ticket in the cookie 
            //if (ticket2 != ticket)
            //{
            //    if (cookielessTicket && ticket2.CookiePath != "/" && ticket2.CookiePath.Length > 1)
            //    {
            //        ticket2 = new FormsAuthenticationTicket(ticket2.Version, ticket2.Name, ticket2.IssueDate,
            //                                                ticket2.Expiration, ticket2.IsPersistent, ticket2.UserData,
            //                                                "/");
            //    }
            //    String strEnc = FormsAuthentication.Encrypt(ticket2);

            //    if (cookielessTicket)
            //    {
            //        e.Context.CookielessHelper.SetCookieValue('F', strEnc);
            //        e.Context.Response.Redirect(e.Context.Request.RawUrl);
            //    }
            //    else
            //    {
            //        if (cookie != null)
            //            cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName];

            //        if (cookie == null)
            //        {
            //            cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEnc);
            //            cookie.Path = ticket2.CookiePath;
            //        }

            //        if (ticket2.IsPersistent)
            //            cookie.Expires = ticket2.Expiration;
            //        cookie.Value = strEnc;
            //        cookie.Secure = FormsAuthentication.RequireSSL;
            //        cookie.HttpOnly = true;
            //        if (FormsAuthentication.CookieDomain != null)
            //            cookie.Domain = FormsAuthentication.CookieDomain;
            //        e.Context.Response.Cookies.Remove(cookie.Name);
            //        e.Context.Response.Cookies.Add(cookie);
            //    }
            //}


        }

        //public void Application_BeginRequest(object sender, EventArgs e)
        //{

        //    HttpApplication application = sender as HttpApplication;

        //    HttpContext context = application.Context; 

        //    HttpResponse response = context.Response;

        //    response.Write("这是来自自定义HttpModule中有BeginRequest");

        //}

        //public void Application_EndRequest(object sender, EventArgs e)
        //{

        //    HttpApplication application = sender as HttpApplication;

        //    HttpContext context = application.Context;

        //    HttpResponse response = context.Response;

        //    response.Write("这是来自自定义HttpModule中有EndRequest");

        //}

    }

}